'use client';

import { useState, useEffect } from 'react';
import { Box, Container, Typography, Button, Alert, Snackbar, CircularProgress, Paper, Radio, RadioGroup, FormControlLabel, FormControl, TextField } from '@mui/material';
import { useRouter } from 'next/navigation';
import { examApi } from '@/api/exams';
import dayjs from 'dayjs';
import { use } from 'react';

interface Question {
  id: number;
  type: string;
  content: string;
  options: string[];
  score: number;
}

interface Answer {
  questionId: number;
  answer: string;
}

export default function ExamPage({ params }: { params: { id: string } }) {
  const examId = use(params).id;
  const [exam, setExam] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [answers, setAnswers] = useState<Answer[]>([]);
  const [timeLeft, setTimeLeft] = useState<number>(0);
  const [examStarted, setExamStarted] = useState(false);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();

  useEffect(() => {
    const fetchExam = async () => {
      try {
        const examData = await examApi.getById(Number(examId));
        setExam(examData);
        // 初始化答案数组
        if (examData.questions) {
          setAnswers(examData.questions.map((q: Question) => ({
            questionId: q.id,
            answer: ''
          })));
        }
      } catch (error) {
        setSnackbar({ open: true, message: '获取考试信息失败', severity: 'error' });
        router.push('/student-exams');
      } finally {
        setLoading(false);
      }
    };

    fetchExam();
  }, [examId, router]);

  useEffect(() => {
    if (examStarted && timeLeft > 0) {
      const timer = setInterval(() => {
        setTimeLeft((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            handleSubmit();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [examStarted, timeLeft]);

  const handleStartExam = () => {
    setExamStarted(true);
    setTimeLeft(exam.duration * 60); // 转换为秒
  };

  const handleAnswerChange = (questionId: number, value: string) => {
    setAnswers(prev =>
      prev.map(a =>
        a.questionId === questionId ? { ...a, answer: value } : a
      )
    );
  };

  const handleSubmit = async () => {
    try {
      await examApi.submitExam(exam.id, {
        answers: answers
      });
      setSnackbar({ open: true, message: '提交成功', severity: 'success' });
      router.push(`/student-exams/${exam.id}/result`);
    } catch (error) {
      setSnackbar({ open: true, message: '提交失败', severity: 'error' });
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen">
        <CircularProgress size={60} />
      </div>
    );
  }

  if (!exam) {
    return null;
  }

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ mb: 4 }}>
        <Typography variant="h4" gutterBottom>
          {exam.title}
        </Typography>
        <Typography variant="subtitle1" color="textSecondary" gutterBottom>
          科目：{exam.subject}
        </Typography>
        <Typography variant="body1" paragraph>
          {exam.description}
        </Typography>
        <Box sx={{ mb: 2 }}>
          <Typography variant="body2">
            考试时长：{exam.duration} 分钟
          </Typography>
          <Typography variant="body2">
            总分：{exam.totalScore}
          </Typography>
          <Typography variant="body2">
            及格分：{exam.passingScore}
          </Typography>
        </Box>
      </Box>

      {!examStarted ? (
        <Box sx={{ textAlign: 'center', my: 4 }}>
          <Button
            variant="contained"
            color="primary"
            size="large"
            onClick={handleStartExam}
          >
            开始答题
          </Button>
        </Box>
      ) : (
        <>
          <Box sx={{ position: 'sticky', top: 0, bgcolor: 'background.paper', zIndex: 1, py: 2, mb: 3 }}>
            <Typography variant="h6" color="primary">
              剩余时间：{formatTime(timeLeft)}
            </Typography>
          </Box>

          <Box sx={{ mb: 4 }}>
            {exam.questions.map((question: Question, index: number) => (
              <Paper key={question.id} sx={{ p: 3, mb: 3 }}>
                <Typography variant="h6" gutterBottom>
                  第 {index + 1} 题（{question.score} 分）
                </Typography>
                <Typography variant="body1" paragraph>
                  {question.content}
                </Typography>

                <FormControl component="fieldset">
                  {question.type === 'CHOICE' && (
                    <RadioGroup
                      value={answers.find(a => a.questionId === question.id)?.answer || ''}
                      onChange={(e) => handleAnswerChange(question.id, e.target.value)}
                    >
                      {(() => {
                        let options = [];
                        if (Array.isArray(question.options)) {
                          options = question.options;
                        } else if (typeof question.options === 'string') {
                          try {
                            options = JSON.parse(question.options);
                            if (!Array.isArray(options)) {
                              options = question.options.split(',').filter(Boolean);
                            }
                          } catch {
                            options = question.options.split(',').filter(Boolean);
                          }
                        }
                        return options.map((option: string, optionIndex: number) => (
                          <FormControlLabel
                            key={optionIndex}
                            value={String.fromCharCode(65 + optionIndex)}
                            control={<Radio />}
                            label={`${String.fromCharCode(65 + optionIndex)}. ${option}`}
                          />
                        ));
                      })()} 
                    </RadioGroup>
                  )}

                  {question.type === 'TRUE_FALSE' && (
                    <RadioGroup
                      value={answers.find(a => a.questionId === question.id)?.answer || ''}
                      onChange={(e) => handleAnswerChange(question.id, e.target.value)}
                    >
                      <FormControlLabel value="true" control={<Radio />} label="正确" />
                      <FormControlLabel value="false" control={<Radio />} label="错误" />
                    </RadioGroup>
                  )}

                  {(question.type === 'FILL_BLANK' || question.type === 'SHORT_ANSWER') && (
                    <TextField
                      fullWidth
                      multiline={question.type === 'SHORT_ANSWER'}
                      rows={question.type === 'SHORT_ANSWER' ? 4 : 1}
                      value={answers.find(a => a.questionId === question.id)?.answer || ''}
                      onChange={(e) => handleAnswerChange(question.id, e.target.value)}
                      placeholder={question.type === 'FILL_BLANK' ? '请输入答案' : '请输入你的答案'}
                    />
                  )}
                </FormControl>
              </Paper>
            ))}
          </Box>

          <Box sx={{ display: 'flex', justifyContent: 'center', mb: 4 }}>
            <Button
              variant="contained"
              color="primary"
              size="large"
              onClick={handleSubmit}
            >
              提交答案
            </Button>
          </Box>
        </>
      )}

      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Container>
  );
}